<?php

namespace app\admin\controller\kefu;

use Throwable;
use think\facade\Db;
use app\worker\library\kefu\Common;
use app\common\controller\Backend;

/**
 * 会话管理
 */
class Session extends Backend
{
    /**
     * Session模型对象
     * @var object
     * @phpstan-var \app\admin\model\kefu\Session
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'delete_time'];

    protected array $withJoinTable = ['user', 'sessionUser'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\kefu\Session();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->visible(['user' => ['nickname'], 'sessionUser' => ['nickname']])
            ->paginate($limit)
            ->each(function ($item) {
                if ($item->user_id && $item->user) {
                    $item->user->nickname = Common::trueValue([
                        $item->user->nickname,
                        $item->user->admin?->nickname,
                        $item->user->sysUser?->nickname,
                        Common::getTouristNickname($item->user->id),
                    ]);
                }

                if ($item->session_user_id && $item->sessionUser) {
                    $item->sessionUser->nickname = Common::trueValue([
                        $item->sessionUser->nickname ?? '',
                        $item->sessionUser->admin?->nickname,
                        $item->sessionUser->sysUser?->nickname,
                        Common::getTouristNickname($item->sessionUser->id),
                    ]);
                }
            });

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 会话聊天记录
     * @throws Throwable
     */
    public function records(): void
    {
        $id   = $this->request->param('id', 0);
        $page = $this->request->param('page', 1);
        $size = $this->request->param('size', 15);

        if (!$id) $this->error('会话找不到啦！');

        if ($page == 1) {
            $min = 0;
        } else {
            $min = ($page - 1) * $size;
        }

        $sessionInfo = Db::name('kefu_session')->find($id);

        list($messages, $users) = Common::loadRecords($id, $sessionInfo['session_user_id'], [
            'min'  => $min,
            'size' => $size,
        ]);
        $nextPage = count($messages) == $size;
        $messages = Common::groupByTime($messages);

        $this->success('', [
            'page'      => $page,
            'users'     => $users,
            'messages'  => $messages,
            'nextPage'  => $nextPage,
            'sessionId' => $id,
            'meId'      => $sessionInfo['session_user_id'],
        ]);
    }
}